package com.swkl.yuan.agvtask.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import com.swkl.yuan.agvtask.entity.AgvSchedulingTaskResponseEntity;
import com.swkl.yuan.agvtask.entity.AgvTask;
import com.swkl.yuan.agvtask.entity.AllConfig;
import com.swkl.yuan.agvtask.task.SendToPlc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @Author Alkin
 * @Date 2023/3/7 10:41
 * @Version 1.0  请求发送任务
 */
@Service
@Slf4j
public class SendRequestTask {
    @Resource
    FinishTraversalTask finishTraversalTask;



    public void sendRequest(AgvTask config, AllConfig allConfig, S7PLC connector){

        try {
            String result = HttpRequest.post(allConfig.requestMoveApi)
                    .body(getRequestParamMap(config.getStartLocation(), config.getEndLocation(), config.getTemplate()))
                    .execute().body();
            AgvSchedulingTaskResponseEntity responseEntity = JSONUtil.toBean(result, AgvSchedulingTaskResponseEntity.class);
            if ("0".equals(responseEntity.getCode())){
                SendToPlc.sendResetSig(connector,config.getPlcMonitorOffset());
                log.info("{}-请求出车,任务id = {}",config.getTaskName(),responseEntity.getData());
                finishTraversalTask.finishTraversal(responseEntity.getData().toString(),config.getPlcFinishOffset(),true,allConfig.requestFinishApi,connector);
            }else {
                //失败请求发送错误程序方法
                SendToPlc.sendErrorSig(connector);
                log.error("{}-返回值异常，反馈PLC异常,错误信息-{}",config.getTaskName(),responseEntity.getMessage());
            }
        }catch (Exception  e){

            log.info("{}-请求出车 开始位置 {} 结束位置 {},出现异常请求地址= {} 异常信息为 ={} ",config.getTaskName(),config.getStartLocation(),config.getEndLocation(),allConfig.requestMoveApi,e.getMessage());

        }




    }
    private String getRequestParamMap(String starting,String finish,String template){
        JSONObject json = new JSONObject();
        ArrayList<Object> objects = new ArrayList<>(2);
        objects.add(new JSONObject().set("positionCode",starting).set("type","00"));
        objects.add(new JSONObject().set("positionCode",finish).set("type","00"));
        json.set("positionCodePath",objects);
        json.set("reqCode", IdUtil.simpleUUID());
        json.set("taskTyp", template);
        return JSONUtil.toJsonStr(json);
    }


}
